<?php

/**
 * 文件上传控制器类
 * 
 * @package    01CMS
 * @subpackage admin
 * @author     rolong at vip.qq.com
 * @version    1.0.0
 * @link       http://www.01cms.com
 */

class FileController extends Controller
{
    public $title = '文件管理';

    function __construct ()
    {
        parent::__construct();
        
        if (! model('User')->isLogined())
        {
            redirect('admin/login');
        }
        
        if (! model('User')->checkAuth())
        {
            exit('您的权限不足');
        }
    }

    /**
     * 获取相关参数
     * 
     * @param string $type
     * @return array
     * @access 	private
     */
    private function getParameters ($type)
    {
        if ($type == 'attachment')
        {
            $this->title = '附件管理';
            $param['pathPrefix'] = PUBLIC_PATH . '/upload';
            $param['urlPrefix'] = PUBLIC_DIR . '/upload';
        }
        else if ($type == 'template')
        {
            $this->title = '模板管理';
            $param['pathPrefix'] = ROOT_PATH . '/template/';
        }
        else
        {
            throw new Exception('参数错误');
        }
        
        $var = $this->Load->query('url,ext,edit,filename,dir,files');
        
        if (! empty($var['dir']))
        {
            $var['dir'] = trim($var['dir'], "\\/.");
        }
        
        $param['path'] = $param['pathPrefix'] . '/' . $var['dir'];
        
        if (! is_dir($param['path']))
        {
            trigger_error('路径不存在或无权操作：' . $param['path']);
        }
        
        if (empty($var))
        {
            $var = array('url'=>'', 'ext'=>'', 'edit'=>'', 'dir'=>'');
        }
        
        return array_merge($var, $param);
    }

    function edit ($action = '', $type = '')
    {
        $this->param = $param = $this->getParameters($type);
        $file = $param['path'] . '/' . $param['filename'];
        
        if ($action == 'update')
        {
            $content = $this->Load->post('content', 'one');
            file_put_contents($file, stripslashes($content));
            responseToParent('保存成功', BOOT_URL . "/file/{$type}/lists?dir={$param['dir']}&ext={$param['ext']}&edit={$param['edit']}");
        }
        else
        {
            $this->content = file_get_contents($file);
            $this->Load->view('Smarty');
        }
    }

    function template ($action = '', $start = 0)
    {
        $this->param = $param = $this->getParameters('template');
        
        if ($action == 'del')
        {
            $this->delFiles($param['path'], $param['files']);
            response('删除成功', TRUE);
        }
        else if ($action == 'lists')
        {
            $this->lists = $this->getFileLists($param['path'], $param['ext'], $start);
            $this->Load->view('Smarty');
        }
    }

    function attachment ($action = '', $start = 0)
    {
        $this->param = $param = $this->getParameters('attachment');
        
        if ($action == 'del')
        {
            $this->delFiles($param['path'], $param['files']);
            response('删除成功', TRUE);
        }
        else if ($action == 'lists')
        {
            $this->lists = $this->getFileLists($param['path'], $param['ext'], $start);
            $this->Load->view('Smarty');
        }
    }

    function fckeditor ($start = 0)
    {
        $this->param = $param = $this->getParameters('attachment');
        $this->lists = $this->getFileLists($param['path'], 'jpg,gif,jpeg,png,JPG,GIF,JPEG,PNG', $start);
        $this->Load->view('Smarty');
    }

    private function getFileLists ($path, $extName = '', $start = 0, $pageSize = 20)
    {
        if ($extName != '')
        {
            $dirs = glob($path . '/[0-9A-Za-z_-]*', GLOB_ONLYDIR);
            $files = glob($path . '/[0-9A-Za-z_-]*{' . $extName . '}', GLOB_BRACE);
            $files = array_merge($dirs, $files);
        }
        else
        {
            $files = glob($path . '/[0-9A-Za-z_-]*' . $extName, GLOB_BRACE);
        }
        
        $count = count($files);
        
        if ($start > $count)
        {
            $start = $count;
        }
        
        $types = array('gif'=>'image', 'jpg'=>'image', 'jpeg'=>'image', 'png'=>'image', 'jpe'=>'image', 'tpl'=>'txt', 'txt'=>'txt', 'html'=>'txt', 'htm'=>'txt', 'php'=>'txt');
        
        $listDir = array();
        $listFile = array();
        
        for ($i = $start; $i < ($pageSize + $start) && $i < $count; $i ++)
        {
            $basename = basename($files[$i]);
            $isDir = is_dir($files[$i]) ? 1 : 0;
            if ($isDir)
            {
                $listDir[] = array('name'=>$basename, 'type'=>'dir');
            }
            else
            {
                $fileSize = filesize($files[$i]);
                $fileExt = strtolower(substr($basename, strrpos($basename, '.') + 1));
                $fileType = isset($types[$fileExt]) ? $types[$fileExt] : '';
                $listFile[] = array('name'=>$basename, 'type'=>$fileType, 'isNew'=>0, 'fileSize'=>$fileSize);
            }
        }
        
        lib('Pagination')->createLinks(array('pageParam'=>2, 'totalRows'=>$count, 'pageSize'=>$pageSize));
        
        return array_merge($listDir, $listFile);
    }

    private function delFiles ($path, $files)
    {
        $files = explode(',', $files);
        
        foreach ($files as $file)
        {
            $fileName = $path . '/' . $file;
            
            if (is_dir($fileName))
            {
                clearDirs($fileName);
                @rmdir($fileName);
            }
            else
            {
                @unlink($fileName);
            }
        }
    }

    function setting ($action = '')
    {
        $this->title .= ' => 上传设置';
        
        if ($action == 'lists')
        {
            $this->data = data('uploadSetting');
            $this->Load->view('Smarty');
        }
        else if ($action == 'update')
        {
            $str = 'uploadPath|文件保存路径规则不能为空,allowedTypes,maxSize,thumbWidth,thumbHeight,thumbPadColor,thumbMarker,';
            $str .= 'width,height,wmText,wmType,wmFontSize,wmFontPath,wmFontColor,wmShadowColor,wmShadowDistance,wmShadowDistance,';
            $str .= 'wmVrtAlignment,wmHorAlignment,wmOpacity,wmPadding,wmOverlayPath,wmHorOffset,wmVrtOffset';
            
            $data = $this->Load->post($str);
            
            if ($error = $this->Load->getError())
            {
                response($error);
            }
            
            $sta = lib('Write')->phpArray(SYS_PATH . '/data/uploadSetting.php', $data);
            
            $message = ($sta > 0) ? '修改成功(' . $sta / 1000 . 'K)' : '修改失败';
            
            response($message);
        }
    }

    function upload ($field = 'Filedata')
    {
        $setting = data('uploadSetting');
        
        $config = array();
        $config['uploadPath'] = PUBLIC_PATH . '/upload/' . date(trim($setting['uploadPath']), TIME) . '/';
        $config['allowedTypes'] = $setting['allowedTypes'];
        $config['maxSize'] = $setting['maxSize'];
        
        makeDirs($config['uploadPath']);
        
        $upload = lib('Upload');
        $upload->initialize($config);
        $upload->doUpload($field);
        
        $data = $upload->data();
        
        if ($upload->errorMsg != '')
        {
            echo "<div><div id='file'></div><div id='error'>{$upload->errorMsg}</div></div>";
            exit();
        }
        
        $fileUrl = str_replace(ROOT_PATH, ROOT_DIR, $data['fullPath']);
        
        if ($data['isImage'])
        {
            $image = lib('ImageLib');
            
            $config = array();
            $config['sourceImage'] = $data['fullPath'];
            
            $config['createThumb'] = ($setting['createThumb'] == '1') ? TRUE : FALSE;
            $config['thumbWidth'] = $setting['thumbWidth'];
            $config['thumbHeight'] = $setting['thumbHeight'];
            $config['thumbPadColor'] = $setting['thumbPadColor'];
            $config['thumbMarker'] = $setting['thumbMarker'];
            
            $config['maintainRatio'] = TRUE;
            $config['width'] = $setting['width'];
            $config['height'] = $setting['height'];
            
            $config['wmType'] = $setting['wmType'];
            $config['wmText'] = $setting['wmText'];
            $config['wmFontSize'] = $setting['wmFontSize'];
            $config['wmFontPath'] = SYS_PATH . '/data/font/' . $setting['wmFontPath'];
            $config['wmFontColor'] = $setting['wmFontColor'];
            $config['wmShadowColor'] = $setting['wmShadowColor'];
            $config['wmShadowDistance'] = $setting['wmShadowDistance'];
            $config['wmVrtAlignment'] = $setting['wmVrtAlignment'];
            $config['wmHorAlignment'] = $setting['wmHorAlignment'];
            $config['wmVrtOffset'] = $setting['wmVrtOffset'];
            $config['wmHorOffset'] = $setting['wmHorOffset'];
            $config['wmOpacity'] = $setting['wmOpacity'];
            $config['wmPadding'] = $setting['wmPadding'];
            $config['wmOverlayPath'] = SYS_PATH . '/data/mark/' . $setting['wmOverlayPath'];
            
            $image->initialize($config);
            
            $image->thumb();
            
            $image->resize();
            
            if ($setting['wmType'] != '0')
            {
                $image->watermark();
            }
            
            if ($image->errorMsg != '')
            {
                echo "<div><div id='file'></div><div id='error'>{$image->errorMsg}</div></div>";
                exit();
            }
            
            echo "<div><div id='file'>{$fileUrl}</div><div id='thumb'>" . getThumb($fileUrl) . "</div><div id='error'></div></div>";
            exit();
        }
        else
        {
            echo "<div><div id='file'>{$fileUrl}</div><div id='thumb'>" . getThumb($fileUrl) . "</div><div id='error'></div></div>";
            exit();
        }
    }
}
